<?php
session_start();

$id=$_SESSION['idUsr'];
$idFav=$_POST['idChangeFav'];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["changeFavPhoto"]["name"]);
$extension = end($temp);
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

if ((($_FILES["changeFavPhoto"]["type"] == "image/gif")
		|| ($_FILES["changeFavPhoto"]["type"] == "image/jpeg")
		|| ($_FILES["changeFavPhoto"]["type"] == "image/jpg")
		|| ($_FILES["changeFavPhoto"]["type"] == "image/pjpeg")
		|| ($_FILES["changeFavPhoto"]["type"] == "image/x-png")
		|| ($_FILES["changeFavPhoto"]["type"] == "image/png"))
		&& in_array($extension, $allowedExts))
{
	if ($_FILES["changeFavPhoto"]["error"] > 0)
	{
		echo "Return Code: " . $_FILES["changeFavPhoto"]["error"] . "<br>";
	}else{
		if (file_exists("../favImages/" . $_FILES["changeFavPhoto"]["name"]))
		{
			echo $_FILES["changeFavPhoto"]["name"] . " already exists. ";
		}else{


		}
	}
}else{
	
	die("invalid file");
}

$img=$_FILES["changeFavPhoto"]["name"];

require_once("DBKonexioa.php");

$konexioa= new DBKonexioa();

if ($konexioa->konektatu()!=TRUE) {
	die("Ha habido un error conectando a la base de datos");
}else{
	
	$sql0="SELECT foto from favor WHERE fk_usuario='$id' AND idfavor='$idFav'";
	$res0=mysql_query($sql0);
	$row=mysql_fetch_assoc($res0);
	$delete="../images/favImages/".$row['foto'];
	$do = unlink($delete);
	if($do != true){
		die ("Ha habido un problema borrando la foto del servidor");
	}
	$sql="UPDATE favor SET foto='$img' WHERE fk_usuario='$id' AND idfavor='$idFav'";
	$res=mysql_query($sql);
	if($res){
		move_uploaded_file($_FILES["changeFavPhoto"]["tmp_name"],
				"../images/favImages/" . $_FILES["changeFavPhoto"]["name"]);
		$extra = "home.php?changed=".$idFav;
		header("Location: http://$host$uri/$extra");

	}else{
		echo mysql_error();
	}
}
$konexioa->konexioaItxi();
?>